package com.iflytek.edu.db.core.context;

import com.iflytek.edu.db.core.context.dto.AdapterInfo;
import com.iflytek.edu.db.core.context.dto.Problem;
import com.iflytek.edu.db.core.enums.AdapterType;
import com.iflytek.edu.db.core.enums.StrategyType;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author linkai
 * @date 2022/2/22
 */
public class AdapterContext {
    private static final ThreadLocal<AdapterInfo> context;

    static {
        context = new ThreadLocal<>();
    }

    public static void init(String sql, AdapterType adapterType) {
        Optional.ofNullable(context.get()).orElseGet(() -> {
            AdapterInfo info = new AdapterInfo();
            info.setSql(sql);
            info.setAdapterType(adapterType);
            context.set(info);
            return info;
        });
    }

    public static AdapterInfo getInfo() {
        return context.get();
    }

    public static void addProblem(StrategyType type, String desc) {
        Problem problemRecord = new Problem();
        problemRecord.setType(type);
        problemRecord.setDesc(desc);
        addProblem(problemRecord);
    }

    public static void addProblem(Problem problem) {
        AdapterInfo info = getInfo();
        List<Problem> records = info.getRecords();
        if (records == null) {
            records = new ArrayList<>();
            info.setRecords(records);
        }
        records.add(problem);
    }

    public static boolean isSearch() {
        AdapterInfo info = getInfo();
        return info != null && Objects.equals(info.getAdapterType(), AdapterType.scan);
    }

    public static void remove() {
        context.remove();
    }
}
